import React, { useState } from "react";
import { Link, useHistory } from "react-router-dom";
import { POST_LOGIN_USER, USER_TOKEN_NAME } from "../../config";

import Grid from "@material-ui/core/Grid";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Button from "@material-ui/core/Button";
import Checkbox from "@material-ui/core/Checkbox";
import TextField from "@material-ui/core/TextField";
import FacebookIcon from "@material-ui/icons/Facebook";

import { formValidation } from "../../helpers/validation";
import { useTranslation } from "react-i18next";
import { useForm } from "react-hook-form";
import { useStatusListener } from "./../../hooks/useStatusListener";
import { useSnackbar } from "notistack";
import { useDispatch, useSelector } from "react-redux";
import { loginUserReq, userLoginAction } from "../../stores/authSlicer";
import request from "../../utils/requests";

type LoginInputTypes = {
  identifier: string;
  password: string;
  ua: string;
};

export default function LoginPage() {
  const { t } = useTranslation();
  const { register, handleSubmit, errors, setValue } = useForm<
    LoginInputTypes
  >();
  const [checked1, setChecked1] = useState(true);

  const backgroundImage = require("../../assets/images/LoginPage/backgroundImage.jpg");
  const logo = require("../../assets/images/LoginPage/logo.svg");
  const googleIcon = require("../../assets/images/LoginPage/google.svg");

  const history = useHistory();
  const dispatch = useDispatch();
  const { enqueueSnackbar } = useSnackbar();

  const authStore = useSelector(
    (state: { authStore: any }) => state.authStore.login
  );

  const { status, data } = authStore;

  const onSuccess = () => {
    localStorage.setItem(USER_TOKEN_NAME, data.data.token);
    if (localStorage.getItem(USER_TOKEN_NAME)) {
      return dispatch(userLoginAction(true)) && history.push(`/dashboard`);
    }
  };

  const onReject = () => {
    if (authStore.error?.message) {
      enqueueSnackbar(authStore.error?.message, {
        variant: "error",
        autoHideDuration: 3000,
      });
    }
  };

  useStatusListener(status, onSuccess, onReject);

  const handleChange1 = (event: React.ChangeEvent<HTMLInputElement>) => {
    setChecked1(event.target.checked);
  };

  const onSubmit = (data: LoginInputTypes) => {
    const finalData = {
      ua: window.navigator.userAgent,
      identifier: data.identifier,
      password: data.password,
    };
    request(loginUserReq, POST_LOGIN_USER, finalData)(dispatch);
  };

  return (
    <>
      <div className="app-wrapper min-vh-100 bg-white">
        <div className="app-inner-content-layout--main app-content p-0">
          <div className="bg-composed-wrapper--content flex-grow-1 w-100 d-flex align-items-center">
            <Grid container spacing={0} className="min-vh-100 ">
              <Grid item lg={5} xl={6} className="d-flex">
                <div className="background-gradient">
                  <img
                    src={backgroundImage}
                    alt="background"
                    className="background-image"
                  />
                  <div className="left-box-content">
                    <div className="greeting-box">
                      <img
                        src={logo}
                        alt="bitbine-logo"
                        className="logo-image"
                      />
                      <div className="greeting-text font-size-xxxl my-4">
                        {t("form:welcome-bitbine")}
                      </div>
                    </div>
                    <div className="left-box-bottom font-size-xxl mx-auto">
                      {t("form:form-desc")}
                    </div>
                  </div>
                </div>
              </Grid>
              <Grid item lg={7} xl={6} className="d-flex align-items-center">
                <Grid
                  item
                  md={10}
                  lg={8}
                  xl={7}
                  className="mx-auto login-box-container"
                >
                  <div className="py-4">
                    <div className="form-header text-center">
                      <div className="display-4 mb-1  form-title">
                        {t("form:login")}
                      </div>
                      <p className="font-size-lg  text-black-50 mt-2">
                        {t("form:login-greeting")}
                      </p>
                    </div>

                    <form onSubmit={handleSubmit(onSubmit)}>
                      <div className="mb-4">
                        <TextField
                          fullWidth
                          id="identifier"
                          name="identifier"
                          placeholder="Username"
                          className="form-input"
                          inputRef={register(formValidation.username)}
                          helperText={
                            errors.identifier?.message &&
                            t(`${errors.identifier?.message}`)
                          }
                          error={Boolean(errors.identifier?.message)}
                        />
                      </div>
                      <div className="mb-3">
                        <TextField
                          fullWidth
                          id="password"
                          name="password"
                          type="password"
                          placeholder="Password"
                          className="form-input"
                          inputRef={register(formValidation.password)}
                          helperText={
                            errors.password?.message &&
                            t(`${errors.password?.message}`)
                          }
                          error={Boolean(errors.password?.message)}
                        />
                      </div>
                      <div className="d-flex justify-content-between align-items-center font-size-md">
                        <FormControlLabel
                          control={
                            <Checkbox
                              checked={checked1}
                              onChange={handleChange1}
                              value="checked1"
                              color="primary"
                            />
                          }
                          label={t("form:remember-me")}
                        />
                        <div>
                          <Link className="text-black-80" to="/forgetPassword">
                            {t("form:forget-pass")}
                          </Link>
                        </div>
                      </div>
                      <div className="login-btns py-4">
                        <Button
                          className="btn-primary form-btn font-size-lg  p-3 my-2"
                          type="submit"
                          onClick={() =>
                            setValue("ua", window.navigator.userAgent)
                          }
                        >
                          {t("form:login")}
                        </Button>
                        <Button
                          component={Link}
                          to="/signup"
                          variant="contained"
                          color="inherit"
                          className="sign-up-btn font-size-lg p-3  my-2"
                        >
                          {t("form:signup")}
                        </Button>
                      </div>

                      <div className="simply-login">
                        <hr className="hr-line" />
                        <div className="text-center font-size-lg main-text">
                          {t("form:simply-login")}
                        </div>
                        <hr className="hr-line" />
                      </div>

                      <div className="text-center py-4  my-4">
                        <Button
                          component={Link}
                          to="/signupFacebook"
                          className="facebook-btn  text-primary"
                          size="small"
                        >
                          <FacebookIcon fontSize="default" />
                          <span className="ml-2 mt-1">Facebook</span>
                        </Button>
                        <Button
                          component={Link}
                          to="/signupGoogle"
                          className="m-2  px-2  google-btn"
                          size="small"
                        >
                          <img
                            src={googleIcon}
                            alt="google-icon"
                            className="google-icon"
                          />
                          <span className="ml-2 mt-1 text-primary pr-3">
                            Google
                          </span>
                        </Button>
                      </div>
                    </form>
                  </div>
                  <div className="form-bottom login-form-bottom">
                    <h6 className="terms">
                      <span className="mr-3">{t("form:terms")}</span>
                    </h6>
                    <h6 className="privacy ml-4">{t("form:privacy")}</h6>
                  </div>
                </Grid>
              </Grid>
            </Grid>
          </div>
        </div>
      </div>
    </>
  );
}
